package file;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Demo4 {
    public static void main(String[] args) throws IOException {
        Scanner scanner=new Scanner(System.in);
        System.out.println("输入要遍历的目录");
        String rootDirPath=scanner.next();
        System.out.println("输入要查找的内容");
        String content=scanner.next();
        File rootDir=new File(rootDirPath);
        if(!rootDir.isDirectory()){
            System.out.println("输入的路径不存在");
            return;
        }
        List<File> results=new ArrayList<>();
        scanDir(rootDir,content,results);
        for(File f:results){
            System.out.println(f.getCanonicalPath());
        }
    }

    private static void scanDir(File rootDir, String content, List<File> results) {
        File[] files=rootDir.listFiles();
        if(files==null||files.length==0){
            return;
        }
        for(File f:files){
            if(f.isDirectory()){
                scanDir(f,content,results);
            }else{
                if(isContentExists(f,content)){
                    results.add(f);
                }
            }
        }
    }

    private static boolean isContentExists(File f, String content) {
        StringBuilder stringBuilder=new StringBuilder();
        try(Reader reader=new FileReader(f)){
            while (true){
                int ch=reader.read();
                if(ch==-1){
                    break;
                }
                stringBuilder.append((char)ch);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.indexOf(content)!=-1;
    }
}
